<template>
  <div class="edit-profile-view-container">
    <div class="background-shapes">
      <div class="shape circle-1"></div>
      <div class="shape circle-2"></div>
    </div>
    
    <div class="edit-profile-container">
      <div class="form-header">
        <h2>编辑个人信息</h2>
        <p>更新您的个人资料</p>
      </div>
      
      <form @submit.prevent="saveProfile">
        <div class="avatar-upload">
          <div class="avatar-preview">
            <img src="/boy.png" class="user-avatar" alt="用户头像">
            <button class="change-avatar-btn" @click.prevent="changeAvatar">
              <i class="fas fa-camera"></i> 更换头像
            </button>
          </div>
        </div>
        
        <div class="input-row">
          <div class="input-group">
            <label>账号名</label>
            <input type="text" v-model="user.account" disabled>
          </div>
        </div>
        
        <div class="input-group">
          <label>昵称</label>
          <input type="text" v-model="user.name" placeholder="输入您的昵称">
        </div>
        
        <div class="input-group">
          <label>邮箱</label>
          <input type="email" v-model="user.bindEmail" placeholder="输入您的邮箱">
        </div>
        
        <div class="input-group">
          <label>手机号</label>
          <input type="tel" v-model="user.bindPhone" placeholder="输入您的手机号">
        </div>
        
        <div class="form-actions">
          <button type="button" class="cancel-btn" @click="cancelEdit" :disabled="loading">
            取消
          </button>
          <button type="submit" class="save-btn" @click="saveProfile" :disabled="loading">
            {{ loading ? '保存中...' : '保存' }}
          </button>
        </div>
      </form>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { 
  selectById, 
  selectAll, 
  insert, 
  deleteById,
  update, 
  selectEq,
  type User,
  type PageInfo
} from '@/http/User';
import { useUserIdStore } from '@/stores/UserId';
import { message } from '@/utils/message';

const userIdStore = useUserIdStore();
const router = useRouter();

const user = ref<User>({
  account: null,
  id: null,
  name: null,
  createTime: null,
  updateTime: null,
  password: null,
  bindPhone: null,
  bindEmail: null,
  role: null,
  avatar: null
});

const loading = ref(false);
const responseData = ref<any>(null);

onMounted(async () => {
  try {
    console.log('🔄 加载用户信息进行编辑...');
    const response = await selectById(userIdStore.currentUserId);
    
    if (response.data) {
      user.value.account = response.data.account;
      user.value.name = response.data.name;
      user.value.bindPhone = response.data.bindPhone;
      user.value.bindEmail = response.data.bindEmail;
      user.value.id = response.data.id;
      
      console.log('✅ 用户信息加载成功');
    } else {
      message.error('加载用户信息失败');
      router.push('/user');
    }
  } catch (error: any) {
    console.error('❌ 加载用户信息失败:', error);
    message.error('加载用户信息失败');
    router.push('/user');
  }
});

const changeAvatar = () => {
  message.info('头像选择功能开发中...');
};

const saveProfile = async () => {
  if (loading.value) return;
  
  // 简单验证
  if (!user.value.name?.trim()) {
    message.warning('请输入姓名');
    return;
  }
  
  if (!user.value.bindEmail?.trim()) {
    message.warning('请输入邮箱');
    return;
  }
  
  if (!user.value.bindPhone?.trim()) {
    message.warning('请输入手机号');
    return;
  }
  
  await testUpdate();
};

const testUpdate = async () => {
  loading.value = true;
  
  try {
    console.log('💾 保存用户信息...');
    
    const pojo: User = {
      name: user.value.name,
      bindEmail: user.value.bindEmail,
      bindPhone: user.value.bindPhone,
      account: null,
      password: null,
      role: null,
      id: null,
      createTime: null,
      updateTime: null,
      avatar: null
    };
    
    const response = await update(userIdStore.currentUserId, pojo);
    responseData.value = response.data;
    
    if (response.data) {
      // 重新获取完整的用户信息
      const updatedUserResponse = await selectById(userIdStore.currentUserId);
      
      if (updatedUserResponse.data) {
        // 更新状态管理中的用户信息
        userIdStore.setUserInfo(updatedUserResponse.data, 'UpdateProfile');
        
        console.log('✅ 个人资料保存成功');
        message.success('个人资料已保存！');
        
        // 延迟跳转，让用户看到成功消息
        setTimeout(() => {
          router.push('/user');
        }, 1500);
      } else {
        message.error('保存成功但获取更新信息失败');
        router.push('/user');
      }
    } else {
      message.error('保存失败，请重试');
    }
  } catch (error: any) {
    console.error('❌ 保存用户信息失败:', error);
    responseData.value = null;
    message.error(`保存失败: ${error.message || '网络错误'}`);
  } finally {
    loading.value = false;
  }
};

const cancelEdit = () => {
  router.push('/user');
};
</script>

<style scoped>
.edit-profile-view-container {
  min-height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  background: linear-gradient(135deg, #f5f7fa 0%, #e4edf5 100%);
  padding: 20px;
  position: relative;
  overflow: hidden;
  font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
}

.background-shapes {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 0;
}

.shape {
  position: absolute;
  border-radius: 50%;
  opacity: 0.1;
}

.circle-1 {
  width: 400px;
  height: 400px;
  background: linear-gradient(45deg, #ff9a9e, #fad0c4);
  top: -200px;
  left: -150px;
}

.circle-2 {
  width: 300px;
  height: 300px;
  background: linear-gradient(45deg, #a1c4fd, #c2e9fb);
  bottom: -150px;
  right: -100px;
}

.edit-profile-container {
  background: rgba(255, 255, 255, 0.85);
  backdrop-filter: blur(10px);
  border-radius: 20px;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
  padding: 40px;
  width: 100%;
  max-width: 650px;
  z-index: 1;
}

.form-header {
  text-align: center;
  margin-bottom: 30px;
}

.form-header h2 {
  font-size: 2rem;
  color: #2c3e50;
  margin-bottom: 10px;
}

.form-header p {
  color: #7f8c8d;
  font-size: 1.1rem;
}

.avatar-upload {
  display: flex;
  justify-content: center;
  margin-bottom: 30px;
}

.avatar-preview {
  text-align: center;
}

.user-avatar {
  width: 150px;
  height: 150px;
  border-radius: 50%;
  object-fit: cover;
  border: 5px solid white;
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
  margin-bottom: 15px;
}

.change-avatar-btn {
  padding: 8px 15px;
  background: #f8f9fa;
  color: #495057;
  border: 1px solid #e1e5eb;
  border-radius: 8px;
  font-size: 0.9rem;
  cursor: pointer;
  transition: all 0.3s ease;
}

.change-avatar-btn:hover {
  background: #e9ecef;
}

.input-row {
  display: flex;
  gap: 20px;
  margin-bottom: 20px;
}

.input-row .input-group {
  flex: 1;
}

.input-group {
  margin-bottom: 25px;
}

.input-group label {
  display: block;
  margin-bottom: 8px;
  font-weight: 500;
  color: #495057;
  font-size: 0.95rem;
}

.input-group input,
.input-group textarea {
  width: 100%;
  padding: 14px;
  border: 1px solid #e1e5eb;
  border-radius: 10px;
  font-size: 1rem;
  transition: all 0.3s ease;
}

.input-group textarea {
  min-height: 100px;
  resize: vertical;
}

.input-group input:focus,
.input-group textarea:focus {
  border-color: #3498db;
  box-shadow: 0 0 0 3px rgba(52, 152, 219, 0.2);
  outline: none;
}

.input-group input[disabled] {
  background-color: #f8f9fa;
  color: #6c757d;
  cursor: not-allowed;
}

.form-actions {
  display: flex;
  justify-content: flex-end;
  gap: 15px;
  margin-top: 20px;
}

.cancel-btn, .save-btn {
  padding: 12px 30px;
  border: none;
  border-radius: 8px;
  font-size: 1rem;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
}

.cancel-btn {
  background: #f8f9fa;
  color: #495057;
  border: 1px solid #e1e5eb;
}

.save-btn {
  background: linear-gradient(to right, #3498db, #1abc9c);
  color: white;
}

.cancel-btn:hover {
  background: #e9ecef;
}

.save-btn:hover {
  transform: translateY(-3px);
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
}

@media (max-width: 768px) {
  .input-row {
    flex-direction: column;
    gap: 0;
  }
  
  .form-actions {
    justify-content: center;
  }
}

@media (max-width: 480px) {
  .edit-profile-container {
    padding: 30px 20px;
  }
}
</style>